package com.bwie.bwedu.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bwie.bwedu.R;
import com.bwie.bwedu.adapter.MyAdapter;
import com.bwie.bwedu.bean.Agency;
import com.bwie.bwedu.bean.Student;
import com.bwie.bwedu.bean.response.AddStuDaiLiResponse;
import com.bwie.bwedu.bean.response.EditStuResponse;
import com.bwie.bwedu.model.CityModel;
import com.bwie.bwedu.model.DistrictModel;
import com.bwie.bwedu.model.ProvinceModel;
import com.bwie.bwedu.presenter.impl.AddStuImpl;
import com.bwie.bwedu.service.XmlParserHandler;
import com.bwie.bwedu.ui.ClearEditText;
import com.bwie.bwedu.ui.RoundImageView;
import com.bwie.bwedu.ui.dialog.ActionSheet.OnOperItemClickL;
import com.bwie.bwedu.ui.dialog.ActionSheetDialog;
import com.bwie.bwedu.utils.ASimpleCacheUtils;
import com.bwie.bwedu.utils.ToastUtils;
import com.bwie.bwedu.view.MainView;
import com.bwie.bwedu.volley.RequestAPI;
import com.google.gson.Gson;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

/**
 * Created by Administrator on 2016/7/21.
 * 学员信息
 */

public class StudentInfoActivity extends BaseActivity implements MainView, OnWheelChangedListener {

    protected static final String IMAGE_FILE_NAME = "photo.png";
    protected static final int REQUESTCODE_PICK = 100;
    protected static final int REQUESTCODE_TAKE = 200;
    private static final int REQUESTCODE_CUTTING = 300;

    private boolean hasHead=false;
    private int type=1;
    private int resultcode;

    private String ss;
    private RoundImageView head;
    private ClearEditText per;
    private ClearEditText per_pho;
    private ClearEditText stu;
    private ClearEditText stu_pho;
    private ClearEditText idca;
    private RadioGroup rg;
    private RadioButton man;
    private RadioButton woman;
    private AutoCompleteTextView agency;
    private Button commit;
    private Button save;
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private String jg;
    private List<Agency> agentList;

    private Student student;
    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode = "";
    private ClearEditText address;
    private AddStuImpl add;
    private Bitmap photo;
    private ImageButton back;
    private TextView title;
    private ArrayAdapter<String> adapter;
    private TextView uoload;
    private Spinner national;


    @Override
    public int getLayout() {
        return R.layout.activity_studentinfo;
    }

    protected void initProvinceDatas() {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            //*/ 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            //*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }

    //--------------------++++++++++++++++--------------------------------------------------------------------
    @Override
    public void findView() {
        head = (RoundImageView) findViewById(R.id.stuinfo_head);
        per = (ClearEditText) findViewById(R.id.stu_per);
        per_pho = (ClearEditText) findViewById(R.id.stu_per_pho);
        stu = (ClearEditText) findViewById(R.id.stu_per_stu);
        stu_pho = (ClearEditText) findViewById(R.id.stu_per_phostu);
        address = (ClearEditText) findViewById(R.id.stu_address);
        idca = (ClearEditText) findViewById(R.id.stu_IDcard);
        rg = (RadioGroup) findViewById(R.id.stu_rg);
        man = (RadioButton) findViewById(R.id.man);
        woman = (RadioButton) findViewById(R.id.woman);
        agency = (AutoCompleteTextView) findViewById(R.id.stu_agency);
        commit = (Button) findViewById(R.id.stu_commit);
        save = (Button) findViewById(R.id.stu_save_local);
        back = (ImageButton) findViewById(R.id.item_title_back);
        title = (TextView) findViewById(R.id.item_title_title);
        uoload = (TextView) findViewById(R.id.item_title_upload);
        national = (Spinner) findViewById(R.id.stu_national);


    }

    private void setText(EditText v, String str) {
        v.setText(str);
    }


    private void showSelectedResult() {
        jg = mCurrentProviceName + mCurrentCityName + mCurrentDistrictName;
        address.setText(jg);
        Toast.makeText(StudentInfoActivity.this, "当前选中:" + mCurrentProviceName + "," + mCurrentCityName + ","
                + mCurrentDistrictName + "," + mCurrentZipCode, Toast.LENGTH_SHORT).show();
    }


    protected String getInfo(EditText str) {
        return str.getText().toString().trim();
    }

    @Override
    public void setData() {
        initAgent();
        uoload.setVisibility(View.VISIBLE);
        national.setAdapter(new ArrayAdapter<String>(this,R.layout.item_daili,R.id.daili_tv,getResources().getStringArray(R.array.spingarr)));
        add = new AddStuImpl(this);
//        student = (Student) getIntent().getSerializableExtra("student");
//        if (student != null) {
//            type=1;
//            title.setText("编辑准学员信息");
//            setText(per, student.gxxm);
//            setText(per_pho, student.gxdh);
//            setText(stu, student.xm);
//            setText(stu_pho, student.grsj);
//            setText(address, student.jg);
//            setText(idca, student.sfzh);
//            setText(agency,student.dlrid);
//            if ("女".equals(student.xb)) {
//                woman.setChecked(true);
//                ss="0";
//            } else if ("男".equals(student.xb)){
//                man.setChecked(true);
//                ss="1";
//            }
//        }else
        if (!TextUtils.isEmpty(getIntent().getStringExtra("id"))){
            type=1;
            title.setText("编辑准学员信息");
            RequestAPI.editStu(getIntent().getStringExtra("id"), new Response.Listener<EditStuResponse>() {
                @Override
                public void onResponse(EditStuResponse editStuResponse) {
                    showToast("success");
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    showToast("erroe");
                }
            });
        }
        else {
            title.setText("录入准学员信息");
            type=2;
            student=new Student();
        }
    }

    @Override
    public void setListener() {
        ///直接上传
        uoload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        national.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position==0){
                    return;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = View.inflate(StudentInfoActivity.this, R.layout.dialog_city, null);
                mViewProvince = (WheelView) view.findViewById(R.id.id_province);
                mViewCity = (WheelView) view.findViewById(R.id.id_city);
                mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
// 添加change事件
                mViewProvince.addChangingListener(StudentInfoActivity.this);
                // 添加change事件
                mViewCity.addChangingListener(StudentInfoActivity.this);
                // 添加change事件
                mViewDistrict.addChangingListener(StudentInfoActivity.this);
                initProvinceDatas();
                mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(StudentInfoActivity.this, mProvinceDatas));
                mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(StudentInfoActivity.this, mProvinceDatas));
                // 设置可见条目数量
                mViewProvince.setVisibleItems(7);
                mViewCity.setVisibleItems(7);
                mViewDistrict.setVisibleItems(7);
				updateCities();
				updateAreas();

                AlertDialog dialog = new AlertDialog.Builder(StudentInfoActivity.this).setTitle("请选择")
                        .setView(view).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showSelectedResult();
//                                if (address.getText().toString().contains("请选择")){
//                                    address.setText("");
//                                }
                            }
                        }).create();
                dialog.show();
            }
        });


        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (man.getId() == checkedId) {
                    ss = "1";
                } else if (woman.getId() == checkedId) {
                    ss = "0";
                }
            }
        });

        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                student.xm=getInfo(stu);
                student.grsj=getInfo(stu_pho);
                student.xb=ss;
                student.jg=getInfo(address);
                student.sfzh=getInfo(idca);
                student.gxxm=getInfo(per);
                student.gxdh=getInfo(per_pho);
//                student.dlrid=getInfo(agency);
                if (hasHead){
                    student.zp=Environment.getExternalStorageDirectory()+"/"+IMAGE_FILE_NAME;
                }
                add.submit(student);
                resultcode=300;
//                add.submit(getInfo(per), getInfo(per_pho), getInfo(stu), getInfo(stu_pho), getInfo(address), getInfo(idca), ss, getInfo(agency));
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                student.xm=getInfo(stu);
                student.grsj=getInfo(stu_pho);
                student.xb=ss;
                student.jg=getInfo(address);
                student.sfzh=getInfo(idca);
                student.gxxm=getInfo(per);
                student.gxdh=getInfo(per_pho);
//                student.dlrid=getInfo(agency);
                if (hasHead){
                    student.zp=Environment.getExternalStorageDirectory()+"/"+IMAGE_FILE_NAME;
                }
                add.saveLocal(student);
                resultcode=400;
//                add.saveLocal(getInfo(per), getInfo(per_pho), getInfo(stu), getInfo(stu_pho), getInfo(address), getInfo(idca), ss, getInfo(agency));
            }
        });

        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] stringItems = {"拍照", "从手机相册选择"};
                final ActionSheetDialog dialog = new ActionSheetDialog(StudentInfoActivity.this, stringItems, findViewById(R.id.student_layout));
                dialog.isTitleShow(false).show();
                dialog.setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                        showToast(stringItems[position]);
                        switch (position) {
                            // 拍照
                            case 0:
                                Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                // 下面这句指定调用相机拍照后的照片存储的路径
                                takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                                        .fromFile(new File(Environment
                                                .getExternalStorageDirectory(), IMAGE_FILE_NAME)));
                                startActivityForResult(takeIntent, REQUESTCODE_TAKE);
                                break;
                            // 相册选择图片
                            case 1:
                                Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
                                // 如果朋友们要限制上传到服务器的图片类型时可以直接写如：image/jpeg 、 image/png等的类型
                                pickIntent
                                        .setDataAndType(
                                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                                "image/*");
                                startActivityForResult(pickIntent, REQUESTCODE_PICK);
                                break;
                            default:
                                break;
                        }
                        dialog.dismiss();
                    }
                });
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBack();
            }
        });

        agency.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    @Override
    public void onSuccess(String id) {
        Intent intent=getIntent();
        student.id=id;
        intent.putExtra("stu",student);
        setResult(resultcode,intent);
        finish();
        overridePendingTransition(R.anim.leftenter,R.anim.rightexit);
    }

    @Override
    public void onFail(final String info) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.getToast(info);

            }
        });
    }


    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
        mViewDistrict.setCurrentItem(0);
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    public void initAgent(){
        new Thread(){
            @Override
            public void run() {
                String read = ASimpleCacheUtils.read("dailirenhuancun");

                if (read!=null){
                    Gson g= new Gson();
                    AddStuDaiLiResponse response = g.fromJson(read, AddStuDaiLiResponse.class);
//                    List<Agency> list =
                    agentList=response.list;
//                    for (int i=0;i<list.size();i++)
//                    {
//                        agentList.add(list.get(i).DLRXM);
//                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            adapter = new ArrayAdapter<String>(StudentInfoActivity.this, android.R.layout.simple_dropdown_item_1line,agentList);
//                            agency.setAdapter(adapter);
                            showToast("======"+agentList.size());
                            MyAdapter adapter = new MyAdapter(StudentInfoActivity.this, agentList);
                            agency.setAdapter(adapter);

                            adapter.setListener(new MyAdapter.OnSelectItemListener() {
                                @Override
                                public void onSelectItem(Agency agency) {
                                    StudentInfoActivity.this.agency.setText(agency.DLRXM);
                                    student.dlrid=agency.DLRID;
                                    StudentInfoActivity.this.agency.dismissDropDown();
                                    StudentInfoActivity.this.agency.setSelection(agency.DLRXM.length());
                                }
                            });

                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.getToast("本地无可用代理人，请手动填写");
                        }
                    });
                }
            }
        }.start();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REQUESTCODE_PICK:// 直接从相册获取
                try {
                    startPhotoZoom(data.getData());
                    String[] proj = {MediaStore.Images.Media.DATA};

                    //好像是android多媒体数据库的封装接口，具体的看Android文档

                    Cursor cursor = managedQuery(data.getData(), proj, null, null, null);

                    //按我个人理解 这个是获得用户选择的图片的索引值

                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                    //将光标移至开头 ，这个很重要，不小心很容易引起越界

                    cursor.moveToFirst();

                    //最后根据索引值获取图片路径

                    String path = cursor.getString(column_index);
                    showToast("==="+path);
                    student.zp=path;
                } catch (NullPointerException e) {
                    e.printStackTrace();// 用户点击取消操作
                }
                break;
            case REQUESTCODE_TAKE:// 调用相机拍照
                File temp = new File(Environment.getExternalStorageDirectory()
                        + "/" + IMAGE_FILE_NAME );
                startPhotoZoom(Uri.fromFile(temp));
                hasHead=true;
                break;
            case REQUESTCODE_CUTTING:// 取得裁剪后的图片
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", true);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            photo = extras.getParcelable("data");
            // Drawable drawable = new BitmapDrawable(null, photo);
            head.setImageBitmap(photo);
        }
    }
    private void onBack(){
        finish();
        overridePendingTransition(R.anim.leftenter,R.anim.rightexit);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK) {
            onBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
